﻿// -----------------------------------------------------------------------
// <copyright file="EUCookieControl.cs" company="Microsoft">
// TODO: Update copyright text.
// </copyright>
// -----------------------------------------------------------------------

namespace LifeInSharePoint.EUCookie.Common.ServerControl
{
    using System;
    using System.ComponentModel;
    using System.Text;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using Microsoft.SharePoint;
    using Microsoft.SharePoint.WebControls;

    /// <summary>
    /// The eu cookie control.
    /// </summary>
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:EUCookieControl runat=server></{0}:EUCookieControl>")]
    public class EUCookieControl : WebControl
    {
        #region Constants
        private const string JqueryFileName = "/_layouts/LifeInSharePoint.EUCookie/js/jquery.js";
        private const string JQueryIncludeScriptKey = "jQueryIncludeScript";

        private const string CookieJsFileName = "/_layouts/LifeInSharePoint.EUCookie/js/jquery.cookie.js";
        private const string CookieJsIncludeScriptKey = "CookieJsIncludeScript";

        private const string CookieCuttrFileName = "/_layouts/LifeInSharePoint.EUCookie/js/jquery.cookiecuttr.js";
        private const string CookieCuttrIncludeScriptKey = "CookieCuttrIncludeScript";

        private const string CookieCustomIncludeScriptKey = "CookieCustomIncludeScript";

        private const string IncludeScriptFormat = @"<script language=""{0}"" src=""{1}{2}""></script>";
        #endregion

        #region Protected Methods
        /// <summary>
        /// The create child controls.
        /// </summary>
        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            CssRegistration.Register(SPContext.Current.Site.RootWeb.Url + "/_layouts/LifeInSharePoint.EUCookie/css/cookiecuttr.css", false);

            ClientScriptManager cs = Page.ClientScript;

            // JQuery
            if (!cs.IsClientScriptBlockRegistered(JQueryIncludeScriptKey) && !this.GetAndPropertyBagBoolValue("CookieDontIncludeJQuery"))
            {
                string includeScript = string.Format(IncludeScriptFormat, "javascript", SPContext.Current.Site.RootWeb.Url, JqueryFileName);
                cs.RegisterClientScriptBlock(this.GetType(), JQueryIncludeScriptKey, includeScript);
            }

            // Cookie JS
            if (!cs.IsClientScriptBlockRegistered(CookieJsIncludeScriptKey))
            {
                string includeCookieScript = string.Format(IncludeScriptFormat, "javascript", SPContext.Current.Site.RootWeb.Url, CookieJsFileName);
                cs.RegisterClientScriptBlock(this.GetType(), CookieJsIncludeScriptKey, includeCookieScript);
            }

            // Cookie Cuttr JS
            if (!cs.IsClientScriptBlockRegistered(CookieCuttrIncludeScriptKey))
            {
                string includeCookieCuttrScript = string.Format(IncludeScriptFormat, "javascript", SPContext.Current.Site.RootWeb.Url, CookieCuttrFileName);
                cs.RegisterClientScriptBlock(this.GetType(), CookieCuttrIncludeScriptKey, includeCookieCuttrScript);
            }

            string googleAnalyticsId = this.GetAndPropertyBagStringValue("GoogleAnalyticsIDPBValue");
            bool enableGoogleAnalyticsUntilDeclined = Convert.ToBoolean(this.GetAndPropertyBagStringValue("EnableGoogleAnalyticsUntilDeclinedPBValue"));

            var javascriptScript = new StringBuilder();
            javascriptScript.Append("<script type='text/javascript'>");
            javascriptScript.Append("$(document).ready(function () {");
            javascriptScript.Append("$.cookieCuttr({");

            if (this.GetAndPropertyBagStringValue("DisplayDiscreetLinkPBValue").ToLower() == "true")
            {
                javascriptScript.Append("cookieDiscreetLink: " + this.GetAndPropertyBagStringValue("DisplayDiscreetLinkPBValue").ToLower() + ",\n");
                javascriptScript.Append("cookieDiscreetLinkText: \"" + this.GetAndPropertyBagStringValue("DiscreetLinkTextPBValue") + "\",\n");
                javascriptScript.Append("cookieDiscreetPosition: \"" + this.GetAndPropertyBagStringValue("DiscreetLinkPositionPBValue") + "\",\n");
            }
            else
            {
                javascriptScript.Append("cookieCutter: " + this.GetAndPropertyBagStringValue("EnablePageElementDisablerPBValue").ToLower() + ",\n");
                javascriptScript.Append("cookieCutterDeclineOnly: " + this.GetAndPropertyBagStringValue("ActivatePageDisablerWhenVisitorDeclinesPBValue").ToLower() + ",\n");
                javascriptScript.Append("cookieAnalytics: " + this.GetAndPropertyBagStringValue("ToggleMessagesPBValue").ToLower() + ",\n");
                javascriptScript.Append("cookieDeclineButton: " + this.GetAndPropertyBagStringValue("ShowDeclineButtonPBValue").ToLower() + ",\n");
                javascriptScript.Append("cookieAcceptButton: " + this.GetAndPropertyBagStringValue("ShowAcceptButtonPBValue").ToLower() + ",\n");
                javascriptScript.Append("cookieResetButton: " + this.GetAndPropertyBagStringValue("ShowResetButtonPBValue").ToLower() + ",\n");
                javascriptScript.Append("cookieOverlayEnabled: " + this.GetAndPropertyBagStringValue("UseLargeOverlayPBValue").ToLower() + ",\n");
                javascriptScript.Append("cookiePolicyLink: \"" + this.GetAndPropertyBagStringValue("PrivacyPolicyLinkPBValue") + "\",\n");
                javascriptScript.Append("cookieMessage: \"" + this.GetAndPropertyBagStringValue("CookiePrivacyLinkMessagePBValue") + "\",\n");
                javascriptScript.Append("cookieAnalyticsMessage: \"" + this.GetAndPropertyBagStringValue("AnalyticsMessagePBValue") + "\",\n");
                javascriptScript.Append("cookieWhatAreTheyLink: \"" + this.GetAndPropertyBagStringValue("WhatAreCookiesLinkPBValue") + "\",\n");
                javascriptScript.Append("cookieErrorMessage: \"" + this.GetAndPropertyBagStringValue("ErrorMessagePBValue") + "\",\n");
                javascriptScript.Append("cookieNotificationLocationBottom: " + this.GetAndPropertyBagStringValue("DisplayNotificationAtBottomOfPagePBValue").ToLower() + ",\n");
                javascriptScript.Append("cookieDisable: \"" + this.GetAndPropertyBagStringValue("DisabledCSSSelectorsPBValue") + "\",\n");
                javascriptScript.Append("cookieAcceptButtonText: \"" + this.GetAndPropertyBagStringValue("AcceptCookieButtonTextPBValue") + "\",\n");
                javascriptScript.Append("cookieDeclineButtonText: \"" + this.GetAndPropertyBagStringValue("DeclineCookieButtonTextPBValue") + "\",\n");
                javascriptScript.Append("cookieResetButtonText: \"" + this.GetAndPropertyBagStringValue("ResetCookieButtonTextPBValue") + "\",\n");
                javascriptScript.Append("cookieWhatAreLinkText: \"" + this.GetAndPropertyBagStringValue("WhatAreCookieLinkTextPBValue") + "\",\n");
                javascriptScript.Append("cookiePolicyPage: " + this.GetAndPropertyBagStringValue("DifferentMessageOnPolicyPagePBValue").ToLower() + ",\n");
                javascriptScript.Append("cookiePolicyPageMessage: \"" + this.GetAndPropertyBagStringValue("PrivacyPolicyMessagePBValue") + "\",\n");
                javascriptScript.Append("cookieDomain: \"" + this.GetAndPropertyBagStringValue("DomainNamePBValue") + "\",\n");
            }

            javascriptScript.Append("});\n");

            if (!string.IsNullOrEmpty(googleAnalyticsId))
            {
                javascriptScript.Append(" if (jQuery.cookie('cc_cookie_accept') == 'cc_cookie_accept') {\n");
                if (!enableGoogleAnalyticsUntilDeclined)
                {
                    javascriptScript.Append(this.getGoogleAnalyticsCode(googleAnalyticsId));
                }

                javascriptScript.Append(" } \n");
                javascriptScript.Append(" if (jQuery.cookie('cc_cookie_decline') == 'cc_cookie_decline') {\n");

                javascriptScript.Append(" } \n");
                if (enableGoogleAnalyticsUntilDeclined)
                {
                    javascriptScript.Append("else {\n");
                    javascriptScript.Append(this.getGoogleAnalyticsCode(googleAnalyticsId));
                    javascriptScript.Append("}\n");
                }
            }

            javascriptScript.Append("});\n");
            javascriptScript.Append("</script>");

            // Cookie Cuttr JS
            if (!cs.IsClientScriptBlockRegistered(CookieCustomIncludeScriptKey))
            {
                cs.RegisterClientScriptBlock(this.GetType(), CookieCustomIncludeScriptKey, javascriptScript.ToString());
            }
        }

        #endregion

        #region Private Methods

        /// <summary>
        /// The get google analytics code.
        /// </summary>
        /// <param name="ID">
        /// The id.
        /// </param>
        /// <returns>
        /// The <see cref="string"/>.
        /// </returns>
        private string getGoogleAnalyticsCode(string ID)
        {
            string googleAnalytics = string.Empty;

            googleAnalytics += "var _gaq = _gaq || [];\n";
            googleAnalytics += "_gaq.push(['_setAccount', '" + ID + "']);\n";
            googleAnalytics += "_gaq.push(['_trackPageview']);\n";

            googleAnalytics += "(function() {\n";
            googleAnalytics += "var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;\n";
            googleAnalytics += "ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';\n";
            googleAnalytics += "var s = document. getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);\n";
            googleAnalytics += "})();\n";

            return googleAnalytics;
        }

        /// <summary>
        /// The get and check value.
        /// </summary>
        /// <param name="propertyBagParam">
        /// The property bag param.
        /// </param>
        /// <returns>
        /// The <see cref="string"/>.
        /// </returns>
        private string GetAndPropertyBagStringValue(string propertyBagParam)
        {
            string pbValue = Utilities.SPPropertyBagHelper.GetPropertyValue(SPContext.Current.Site.RootWeb, propertyBagParam);
            if (string.IsNullOrEmpty(pbValue))
            {
                pbValue = string.Empty;
            }

            return pbValue;
        }

        private bool GetAndPropertyBagBoolValue(string propertyBagParam)
        {
            bool pbValue = Convert.ToBoolean(Utilities.SPPropertyBagHelper.GetPropertyValue(SPContext.Current.Site.RootWeb, propertyBagParam));
            return pbValue;
        }

        #endregion
    }
}
